package com.xcc.id;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.log.LogFactory;

import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.logging.Logger;

/**
 * id生成
 */
public class IdGenerate {
    /**
     * 工作id
     */
    private static long workerId = 1L;
    /**
     * 数据中心id
     */
    private static long datacenterId = 0L;

    private static Snowflake snowflake = IdUtil.createSnowflake(workerId, datacenterId);

    static {
        try {
            workerId = NetUtil.ipv4ToLong(NetUtil.getLocalhostStr()) % (2<<5-1);
            System.out.println("当前主机的workerId： " + workerId);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("获取workerId失败");
            workerId = NetUtil.getLocalhostStr().hashCode() % (2<<5-1);
        }
    }

    public synchronized static long snowflakeId() {
        return snowflake.nextId();
    }

    /*public static void main(String[] args) {
        Set<Long> set = new CopyOnWriteArraySet<>();
        for (int i = 0; i < 10000; i++) {
            new Thread(()->{
                long l = IdGenerate.snowflakeId();
                set.add(l);
                System.out.println(Thread.currentThread().getName()+"\t"+l);
            },String.valueOf(i)).start();
        }
        while (Thread.activeCount() > 2) {
            Thread.yield();
        }
        System.out.println("======================");
        System.out.println("set \t" + set.size());
    }*/
}
